package covertjava.intercept;

import org.apache.log4j.*;

import java.io.*;

/**
 * <p>Output stream implementation that redirects output to Log4J</p>
 * <p>Copyright: Copyright (c) 2004 Sams Publishing</p>
 * @author Alex Kalinovsky
 * @version 1.0
 */
public class LogOutputStream extends OutputStream {

    static Logger logger = Logger.getLogger(LogOutputStream.class.getName());

    protected StringBuffer buffer;
    protected String lineSeparator;
    protected char lineSeparatorEnd;


    public LogOutputStream() {
        this(256);
        lineSeparator = System.getProperty("line.separator");
        lineSeparatorEnd = lineSeparator.charAt(lineSeparator.length() - 1);
    }

    public LogOutputStream(int bufferSize) {
        this.buffer = new StringBuffer(bufferSize);
    }

    public void write(int b) throws IOException {
        char ch = (char)b;
        this.buffer.append(ch);
        if (ch == this.lineSeparatorEnd) {
            // Check on a char by char basis for speed
            String s = buffer.toString();
            if (s.indexOf(lineSeparator) != -1) {
                // The whole separator string is written
                logger.info(s.substring(0, s.length() - lineSeparator.length()));
                buffer.setLength(0);
            }
        }
    }

    public static void main(String[] args) {
        System.out.println("Installing the interceptor...");
        PrintStream out = new PrintStream(new LogOutputStream(), true);
        System.setOut(out);
        System.out.println("Hello, world");
        System.out.println("Done");
    }

}
